package com.imy.virtual.helper.io;

import android.util.Log;


import java.io.File;
import java.util.ArrayList;
import java.util.List;

import de.robv.android.xposed.DexposedBridge;
import de.robv.android.xposed.XC_MethodHook;

public class IOHelper  {
  private String TAG="IOHelper";
  private List<Redirect> path = new ArrayList<>();
  private static final IOHelper sMgr = new IOHelper();

  public static IOHelper get() {
    return sMgr;
  }
  private IOHelper(){

  }
  public IOHelper redirectPath(String origPath ,String newPath) {
    path.add(Redirect.build(origPath,newPath));
    return this;
  }
  public void start(){
    DexposedBridge.hookAllConstructors(File.class, new XC_MethodHook() {
      @Override
      protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
        super.beforeHookedMethod(param);
        int length = param.args.length;
        Log.i(TAG, "hookAllConstructors :" +length);
        if (length==1){
          String arg = (String) param.args[0];
          Log.i(TAG,"长度1个 arg:"+arg);
          String redirect = redirect(arg);
          if (!redirect.equals("")){
            param.args[0]=redirect;
          }else {
            Log.i(TAG,"无匹配:"+arg);
          }

        }else if (length==2){
            Object arg = param.args[0];
            Log.i(TAG,"长度2个:"+ arg+"  第二个:"+param.args[1]);
            if (arg instanceof String){
              String a = (String) arg;
            }
        }

      }
    });


    //try {


  }

  private String redirect(String arg) {
    for (int i = 0; i < path.size(); i++) {
      Redirect redirect = path.get(i);
      String origPath = redirect.origPath;
      if (origPath.equals(arg)){
        Log.i(TAG,"替换"+arg+ " ---->"+redirect.newPath );
        return redirect.newPath;
      }
    }
    return "";
  }

  public static class Redirect{
    String origPath;
    String newPath;

    public Redirect(String origPath, String newPath) {
      this.origPath = origPath;
      this.newPath = newPath;
    }
    public static Redirect build(String origPath,String newPath){
     return new Redirect(origPath, newPath);
    }
  }
}
